const express = require('express');
const mysql = require('mysql2/promise');
const cors = require('cors');
const bcrypt = require('bcrypt');

const app = express();
const PORT = 3000;

// 中间件
app.use(cors());
app.use(express.json());

// 数据库连接配置
const dbConfig = {
  host: 'localhost',
  user: 'root',
  password: '123456', // 替换为您的数据库密码
  database: 'chatime',
  port: 3306
};

// 创建数据库连接池
const pool = mysql.createPool(dbConfig);

// 测试数据库连接
pool.getConnection()
  .then(connection => {
    console.log('✅ 数据库连接成功');
    connection.release();
  })
  .catch(err => {
    console.error('❌ 数据库连接失败:', err);
  });

// API路由

// 用户登录
app.post('/api/user/login', async (req, res) => {
  try {
    const { phone, password } = req.body;
    
    const [rows] = await pool.execute(
      'SELECT * FROM users WHERE phone = ?',
      [phone]
    );
    
    if (rows.length === 0) {
      return res.json({
        success: false,
        message: '用户不存在'
      });
    }
    
    const user = rows[0];
    
    // 临时方案：对于示例用户，使用简单密码验证
    let isValidPassword = false;
    if (user.password.includes('example_hash')) {
      // 示例用户使用简单密码验证
      isValidPassword = (password === '123456');
    } else {
      // 真实用户使用bcrypt验证
      isValidPassword = await bcrypt.compare(password, user.password);
    }
    
    if (!isValidPassword) {
      return res.json({
        success: false,
        message: '密码错误'
      });
    }
    
    // 返回用户信息（不包含密码）
    const userInfo = {
      id: user.id,
      phone: user.phone,
      name: user.name,
      avatar: user.avatar,
      signature: user.signature,
      following: user.following,
      followers: user.followers,
      dynamics: user.dynamics,
      collections: user.collections,
      photos: user.photos,
      createTime: user.create_time,
      updateTime: user.update_time
    };
    
    res.json({
      success: true,
      data: userInfo,
      message: '登录成功'
    });
    
  } catch (error) {
    console.error('登录错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器错误'
    });
  }
});

// 用户注册
app.post('/api/user/register', async (req, res) => {
  try {
    const { phone, password, name, avatar, signature } = req.body;
    
    // 检查用户是否已存在
    const [existingUsers] = await pool.execute(
      'SELECT id FROM users WHERE phone = ?',
      [phone]
    );
    
    if (existingUsers.length > 0) {
      return res.json({
        success: false,
        message: '手机号已注册'
      });
    }
    
    // 生成用户ID
    const userId = 'user_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
    
    // 加密密码
    const hashedPassword = await bcrypt.hash(password, 10);
    
    // 插入新用户
    const [result] = await pool.execute(
      'INSERT INTO users (id, phone, password, name, avatar, signature, create_time, update_time) VALUES (?, ?, ?, ?, ?, ?, NOW(), NOW())',
      [userId, phone, hashedPassword, name, avatar || '', signature || '']
    );
    
    console.log('✅ 用户注册成功，用户ID:', userId);
    
    res.json({
      success: true,
      message: '注册成功',
      data: { userId: userId }
    });
    
  } catch (error) {
    console.error('注册错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器错误'
    });
  }
});

// 获取用户信息
app.get('/api/user/:userId', async (req, res) => {
  try {
    const { userId } = req.params;
    
    const [rows] = await pool.execute(
      'SELECT * FROM users WHERE id = ?',
      [userId]
    );
    
    if (rows.length === 0) {
      return res.json({
        success: false,
        message: '用户不存在'
      });
    }
    
    const user = rows[0];
    const userInfo = {
      id: user.id,
      phone: user.phone,
      name: user.name,
      avatar: user.avatar,
      signature: user.signature,
      following: user.following,
      followers: user.followers,
      dynamics: user.dynamics,
      collections: user.collections,
      photos: user.photos,
      createTime: user.create_time,
      updateTime: user.update_time
    };
    
    res.json({
      success: true,
      data: userInfo
    });
    
  } catch (error) {
    console.error('获取用户信息错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器错误'
    });
  }
});

// 获取聊天列表
app.get('/api/chat/list/:userId', async (req, res) => {
  try {
    const { userId } = req.params;
    
    const [rows] = await pool.execute(`
      SELECT DISTINCT 
        c.id,
        c.sender_id,
        c.receiver_id,
        c.content,
        c.type,
        c.timestamp,
        c.is_read,
        sender.name as sender_name,
        sender.avatar as sender_avatar,
        receiver.name as receiver_name,
        receiver.avatar as receiver_avatar
      FROM chat_messages c
      LEFT JOIN users sender ON c.sender_id = sender.id
      LEFT JOIN users receiver ON c.receiver_id = receiver.id
      WHERE c.sender_id = ? OR c.receiver_id = ?
      ORDER BY c.timestamp DESC
    `, [userId, userId]);
    
    res.json({
      success: true,
      data: rows
    });
    
  } catch (error) {
    console.error('获取聊天列表错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器错误'
    });
  }
});

// 获取聊天消息详情
app.get('/api/chat/messages/:userId/:targetUserId', async (req, res) => {
  try {
    const { userId, targetUserId } = req.params;
    
    const [rows] = await pool.execute(`
      SELECT 
        c.id,
        c.sender_id,
        c.receiver_id,
        c.content,
        c.type,
        c.timestamp,
        c.is_read,
        u.name as sender_name,
        u.avatar as sender_avatar
      FROM chat_messages c
      LEFT JOIN users u ON c.sender_id = u.id
      WHERE (c.sender_id = ? AND c.receiver_id = ?) 
         OR (c.sender_id = ? AND c.receiver_id = ?)
      ORDER BY c.timestamp ASC
    `, [userId, targetUserId, targetUserId, userId]);
    
    res.json({
      success: true,
      data: rows
    });
    
  } catch (error) {
    console.error('获取聊天消息详情错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器错误'
    });
  }
});

// 发送聊天消息
app.post('/api/chat/send', async (req, res) => {
  try {
    const { senderId, receiverId, content, type = 'text' } = req.body;
    
    if (!senderId || !receiverId || !content) {
      return res.json({
        success: false,
        message: '参数不完整'
      });
    }
    
    // 插入消息
    const [result] = await pool.execute(
      'INSERT INTO chat_messages (sender_id, receiver_id, content, type, timestamp) VALUES (?, ?, ?, ?, NOW())',
      [senderId, receiverId, content, type]
    );
    
    // 更新或创建聊天会话
    await pool.execute(`
      INSERT INTO chat_sessions (user_id, target_user_id, last_message, last_message_time, unread_count) 
      VALUES (?, ?, ?, NOW(), 1)
      ON DUPLICATE KEY UPDATE 
        last_message = VALUES(last_message),
        last_message_time = VALUES(last_message_time),
        unread_count = unread_count + 1
    `, [receiverId, senderId, content]);
    
    res.json({
      success: true,
      message: '发送成功',
      data: { messageId: result.insertId }
    });
    
  } catch (error) {
    console.error('发送消息错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器错误'
    });
  }
});

// 标记消息为已读
app.post('/api/chat/read', async (req, res) => {
  try {
    const { userId, targetUserId } = req.body;
    
    if (!userId || !targetUserId) {
      return res.json({
        success: false,
        message: '参数不完整'
      });
    }
    
    // 标记消息为已读
    await pool.execute(
      'UPDATE chat_messages SET is_read = true WHERE sender_id = ? AND receiver_id = ? AND is_read = false',
      [targetUserId, userId]
    );
    
    // 重置未读消息数
    await pool.execute(
      'UPDATE chat_sessions SET unread_count = 0 WHERE user_id = ? AND target_user_id = ?',
      [userId, targetUserId]
    );
    
    res.json({
      success: true,
      message: '标记成功'
    });
    
  } catch (error) {
    console.error('标记已读错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器错误'
    });
  }
});

// 获取好友列表
app.get('/api/friend/list/:userId', async (req, res) => {
  try {
    const { userId } = req.params;
    
    const [rows] = await pool.execute(`
      SELECT 
        f.id,
        f.user_id,
        f.friend_id,
        u.name as friend_name,
        u.avatar as friend_avatar,
        u.signature as friend_signature,
        f.add_time,
        0 as is_online
      FROM friends f
      LEFT JOIN users u ON f.friend_id = u.id
      WHERE f.user_id = ?
    `, [userId]);
    
    res.json({
      success: true,
      data: rows
    });
    
  } catch (error) {
    console.error('获取好友列表错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器错误'
    });
  }
});

// 搜索用户
app.post('/api/friend/search/:userId', async (req, res) => {
  try {
    const { userId } = req.params;
    const { keyword } = req.body;
    
    if (!keyword || keyword.trim().length === 0) {
      return res.json({
        success: false,
        message: '搜索关键词不能为空'
      });
    }
    
    // 搜索用户（通过手机号或昵称）
    const [rows] = await pool.execute(`
      SELECT 
        id as friend_id,
        name as friend_name,
        avatar as friend_avatar,
        signature as friend_signature,
        phone
      FROM users 
      WHERE (phone LIKE ? OR name LIKE ?) AND id != ?
      LIMIT 20
    `, [`%${keyword}%`, `%${keyword}%`, userId]);
    
    res.json({
      success: true,
      data: rows
    });
    
  } catch (error) {
    console.error('搜索用户错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器错误'
    });
  }
});

// 发送好友申请
app.post('/api/friend/request', async (req, res) => {
  try {
    console.log('收到好友申请请求:', req.body);
    const { userId, targetUserId, message } = req.body;
    
    if (!userId || !targetUserId) {
      return res.json({
        success: false,
        message: '参数不完整'
      });
    }
    
    // 检查是否已经是好友
    const [existingFriends] = await pool.execute(
      'SELECT id FROM friends WHERE user_id = ? AND friend_id = ?',
      [userId, targetUserId]
    );
    
    if (existingFriends.length > 0) {
      return res.json({
        success: false,
        message: '已经是好友了'
      });
    }
    
    // 检查是否已经发送过申请
    const [existingRequests] = await pool.execute(
      'SELECT id FROM friend_requests WHERE sender_id = ? AND receiver_id = ? AND status = "pending"',
      [userId, targetUserId]
    );
    
    if (existingRequests.length > 0) {
      return res.json({
        success: false,
        message: '已经发送过好友申请了'
      });
    }
    
    // 创建好友申请
    const requestId = 'request_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
    
    await pool.execute(
      'INSERT INTO friend_requests (id, sender_id, receiver_id, message, create_time) VALUES (?, ?, ?, ?, NOW())',
      [requestId, userId, targetUserId, message || '']
    );
    
    // 更新接收者的待处理申请数量
    await pool.execute(
      'UPDATE users SET pending_requests_count = pending_requests_count + 1 WHERE id = ?',
      [targetUserId]
    );
    
    res.json({
      success: true,
      message: '好友申请发送成功'
    });
    
  } catch (error) {
    console.error('发送好友申请错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器错误'
    });
  }
});

// 获取好友申请列表
app.get('/api/friend/requests/:userId', async (req, res) => {
  try {
    const { userId } = req.params;
    
    const [rows] = await pool.execute(`
      SELECT 
        fr.id,
        fr.sender_id,
        fr.receiver_id,
        fr.message,
        fr.status,
        fr.create_time,
        u.name as sender_name,
        u.avatar as sender_avatar,
        u.signature as sender_signature
      FROM friend_requests fr
      LEFT JOIN users u ON fr.sender_id = u.id
      WHERE fr.receiver_id = ? AND fr.status = 'pending'
      ORDER BY fr.create_time DESC
    `, [userId]);
    
    res.json({
      success: true,
      data: rows
    });
    
  } catch (error) {
    console.error('获取好友申请列表错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器错误'
    });
  }
});

// 处理好友申请
app.post('/api/friend/request/respond', async (req, res) => {
  try {
    const { userId, requestId, action } = req.body; // action: 'accept' or 'reject'
    
    if (!userId || !requestId || !action) {
      return res.json({
        success: false,
        message: '参数不完整'
      });
    }
    
    // 获取申请信息
    const [requests] = await pool.execute(
      'SELECT * FROM friend_requests WHERE id = ? AND receiver_id = ? AND status = "pending"',
      [requestId, userId]
    );
    
    if (requests.length === 0) {
      return res.json({
        success: false,
        message: '申请不存在或已处理'
      });
    }
    
    const request = requests[0];
    const newStatus = action === 'accept' ? 'accepted' : 'rejected';
    
    // 更新申请状态
    await pool.execute(
      'UPDATE friend_requests SET status = ?, update_time = NOW() WHERE id = ?',
      [newStatus, requestId]
    );
    
    if (action === 'accept') {
      // 检查是否已经是好友
      const [existingFriends1] = await pool.execute(
        'SELECT id FROM friends WHERE user_id = ? AND friend_id = ?',
        [request.sender_id, request.receiver_id]
      );
      
      const [existingFriends2] = await pool.execute(
        'SELECT id FROM friends WHERE user_id = ? AND friend_id = ?',
        [request.receiver_id, request.sender_id]
      );
      
      if (existingFriends1.length === 0 && existingFriends2.length === 0) {
        // 添加好友关系（双向）
        const friendId1 = 'friend_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
        const friendId2 = 'friend_' + (Date.now() + 1) + '_' + Math.random().toString(36).substr(2, 9);
        
        await pool.execute(
          'INSERT INTO friends (id, user_id, friend_id, add_time) VALUES (?, ?, ?, NOW())',
          [friendId1, request.sender_id, request.receiver_id]
        );
      
        await pool.execute(
          'INSERT INTO friends (id, user_id, friend_id, add_time) VALUES (?, ?, ?, NOW())',
          [friendId2, request.receiver_id, request.sender_id]
        );
        
        // 发送问好消息
        const messageId = 'msg_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
        const greetingMessage = '你好！很高兴认识你，我们已经是好友了！';
        
        await pool.execute(
          'INSERT INTO chat_messages (id, sender_id, receiver_id, content, type, create_time) VALUES (?, ?, ?, ?, "text", NOW())',
          [messageId, request.receiver_id, request.sender_id, greetingMessage]
        );
      }
    }
    
    // 更新接收者的待处理申请数量
    await pool.execute(
      'UPDATE users SET pending_requests_count = pending_requests_count - 1 WHERE id = ?',
      [userId]
    );
    
    res.json({
      success: true,
      message: action === 'accept' ? '已同意好友申请' : '已拒绝好友申请'
    });
    
  } catch (error) {
    console.error('处理好友申请错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器错误'
    });
  }
});

// 获取待处理申请数量
app.get('/api/friend/requests/count/:userId', async (req, res) => {
  try {
    const { userId } = req.params;
    
    const [rows] = await pool.execute(
      'SELECT pending_requests_count FROM users WHERE id = ?',
      [userId]
    );
    
    if (rows.length === 0) {
      return res.json({
        success: false,
        message: '用户不存在'
      });
    }
    
    res.json({
      success: true,
      data: { count: rows[0].pending_requests_count }
    });
    
  } catch (error) {
    console.error('获取申请数量错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器错误'
    });
  }
});

// 获取动态列表
app.get('/api/dynamic/list/:userId', async (req, res) => {
  try {
    const { userId } = req.params;
    
    const [rows] = await pool.execute(`
      SELECT 
        d.id,
        d.user_id,
        u.name as user_name,
        u.avatar as user_avatar,
        d.content,
        d.images,
        d.like_count,
        d.comment_count,
        d.create_time,
        CASE WHEN l.id IS NOT NULL THEN 1 ELSE 0 END as is_liked
      FROM dynamics d
      LEFT JOIN users u ON d.user_id = u.id
      LEFT JOIN dynamic_likes l ON d.id = l.dynamic_id AND l.user_id = ?
      ORDER BY d.create_time DESC
    `, [userId]);

    // 为每个动态获取评论数据
    for (let i = 0; i < rows.length; i++) {
      const [comments] = await pool.execute(`
        SELECT 
          c.id,
          c.user_id,
          u.name as user_name,
          c.content,
          c.create_time
        FROM dynamic_comments c
        LEFT JOIN users u ON c.user_id = u.id
        WHERE c.dynamic_id = ?
        ORDER BY c.create_time ASC
      `, [rows[i].id]);
      
      rows[i].comments = comments;
    }
    
    res.json({
      success: true,
      data: rows
    });
    
  } catch (error) {
    console.error('获取动态列表错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器错误'
    });
  }
});

// 发布动态
app.post('/api/dynamic/publish', async (req, res) => {
  try {
    const { userId, content, images } = req.body;
    
    if (!userId || !content) {
      return res.json({
        success: false,
        message: '参数不完整'
      });
    }
    
    // 插入动态
    const [result] = await pool.execute(
      'INSERT INTO dynamics (user_id, content, images, create_time) VALUES (?, ?, ?, NOW())',
      [userId, content, images ? JSON.stringify(images) : null]
    );
    
    // 更新用户的动态数量
    await pool.execute(
      'UPDATE users SET dynamics = dynamics + 1 WHERE id = ?',
      [userId]
    );
    
    res.json({
      success: true,
      message: '发布成功',
      data: { dynamicId: result.insertId }
    });
    
  } catch (error) {
    console.error('发布动态错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器错误'
    });
  }
});

// 点赞动态
app.post('/api/dynamic/like', async (req, res) => {
  try {
    const { userId, dynamicId } = req.body;
    
    if (!userId || !dynamicId) {
      return res.json({
        success: false,
        message: '参数不完整'
      });
    }
    
    console.log('👍 处理点赞请求:', { userId, dynamicId });
    
    // 检查是否已经点赞
    const [existingLikes] = await pool.execute(
      'SELECT id FROM dynamic_likes WHERE user_id = ? AND dynamic_id = ?',
      [userId, dynamicId]
    );
    
    if (existingLikes.length > 0) {
      // 取消点赞
      await pool.execute(
        'DELETE FROM dynamic_likes WHERE user_id = ? AND dynamic_id = ?',
        [userId, dynamicId]
      );
      
      await pool.execute(
        'UPDATE dynamics SET like_count = like_count - 1 WHERE id = ?',
        [dynamicId]
      );
      
      console.log('✅ 取消点赞成功');
      
      res.json({
        success: true,
        message: '取消点赞成功',
        data: { liked: false }
      });
    } else {
      // 添加点赞
      const likeId = 'like_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
      
      await pool.execute(
        'INSERT INTO dynamic_likes (id, user_id, dynamic_id, create_time) VALUES (?, ?, ?, NOW())',
        [likeId, userId, dynamicId]
      );
      
      await pool.execute(
        'UPDATE dynamics SET like_count = like_count + 1 WHERE id = ?',
        [dynamicId]
      );
      
      console.log('✅ 点赞成功，点赞ID:', likeId);
      
      res.json({
        success: true,
        message: '点赞成功',
        data: { liked: true }
      });
    }
    
  } catch (error) {
    console.error('❌ 点赞动态错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器错误'
    });
  }
});

// 评论动态
app.post('/api/dynamic/comment', async (req, res) => {
  try {
    const { userId, dynamicId, content } = req.body;
    
    if (!userId || !dynamicId || !content) {
      return res.json({
        success: false,
        message: '参数不完整'
      });
    }
    
    console.log('💬 处理评论请求:', { userId, dynamicId, content });
    
    // 生成唯一评论ID
    const commentId = 'comment_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
    
    // 插入评论
    const [result] = await pool.execute(
      'INSERT INTO dynamic_comments (id, dynamic_id, user_id, content, create_time) VALUES (?, ?, ?, ?, NOW())',
      [commentId, dynamicId, userId, content]
    );
    
    // 更新动态的评论数量
    await pool.execute(
      'UPDATE dynamics SET comment_count = comment_count + 1 WHERE id = ?',
      [dynamicId]
    );
    
    console.log('✅ 评论成功，评论ID:', commentId);
    
    res.json({
      success: true,
      message: '评论成功',
      data: { commentId: commentId }
    });
    
  } catch (error) {
    console.error('❌ 评论动态错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器错误'
    });
  }
});

// 关注某人
app.post('/api/follow', async (req, res) => {
  try {
    const { userId, targetUserId } = req.body;
    if (!userId || !targetUserId) {
      return res.json({ success: false, message: '参数不完整' });
    }
    if (userId === targetUserId) {
      return res.json({ success: false, message: '不能关注自己' });
    }
    // 检查是否已关注
    const [exist] = await pool.execute('SELECT id FROM follows WHERE user_id = ? AND follow_id = ?', [userId, targetUserId]);
    if (exist.length > 0) {
      return res.json({ success: false, message: '已关注' });
    }
    // 插入关注关系
    const followId = 'follow_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
    await pool.execute('INSERT INTO follows (id, user_id, follow_id, create_time) VALUES (?, ?, ?, NOW())', [followId, userId, targetUserId]);
    // 更新关注数/粉丝数
    await pool.execute('UPDATE users SET following = following + 1 WHERE id = ?', [userId]);
    await pool.execute('UPDATE users SET followers = followers + 1 WHERE id = ?', [targetUserId]);
    // 检查对方是否已关注自己，若是则建立好友关系
    const [mutual] = await pool.execute('SELECT id FROM follows WHERE user_id = ? AND follow_id = ?', [targetUserId, userId]);
    if (mutual.length > 0) {
      // 检查是否已是好友
      const [friendExist] = await pool.execute('SELECT id FROM friends WHERE user_id = ? AND friend_id = ?', [userId, targetUserId]);
      if (friendExist.length === 0) {
        const friendId1 = 'friend_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
        const friendId2 = 'friend_' + (Date.now() + 1) + '_' + Math.random().toString(36).substr(2, 9);
        await pool.execute('INSERT INTO friends (id, user_id, friend_id, add_time) VALUES (?, ?, ?, NOW())', [friendId1, userId, targetUserId]);
        await pool.execute('INSERT INTO friends (id, user_id, friend_id, add_time) VALUES (?, ?, ?, NOW())', [friendId2, targetUserId, userId]);
      }
    }
    res.json({ success: true, message: '关注成功' });
  } catch (error) {
    console.error('关注错误:', error);
    res.status(500).json({ success: false, message: '服务器错误' });
  }
});

// 取消关注
app.post('/api/unfollow', async (req, res) => {
  try {
    const { userId, targetUserId } = req.body;
    if (!userId || !targetUserId) {
      return res.json({ success: false, message: '参数不完整' });
    }
    // 删除关注关系
    const [result] = await pool.execute('DELETE FROM follows WHERE user_id = ? AND follow_id = ?', [userId, targetUserId]);
    if (result.affectedRows === 0) {
      return res.json({ success: false, message: '未关注' });
    }
    // 更新关注数/粉丝数
    await pool.execute('UPDATE users SET following = following - 1 WHERE id = ?', [userId]);
    await pool.execute('UPDATE users SET followers = followers - 1 WHERE id = ?', [targetUserId]);
    // 检查是否还互关，若不再互关则移除好友关系
    const [mutual] = await pool.execute('SELECT id FROM follows WHERE user_id = ? AND follow_id = ?', [targetUserId, userId]);
    if (mutual.length === 0) {
      await pool.execute('DELETE FROM friends WHERE (user_id = ? AND friend_id = ?) OR (user_id = ? AND friend_id = ?)', [userId, targetUserId, targetUserId, userId]);
    }
    res.json({ success: true, message: '已取消关注' });
  } catch (error) {
    console.error('取关错误:', error);
    res.status(500).json({ success: false, message: '服务器错误' });
  }
});

// 获取关注列表
app.get('/api/following/:userId', async (req, res) => {
  try {
    const { userId } = req.params;
    const [rows] = await pool.execute(`
      SELECT f.follow_id as user_id, u.name, u.avatar, u.signature
      FROM follows f
      LEFT JOIN users u ON f.follow_id = u.id
      WHERE f.user_id = ?
    `, [userId]);
    res.json({ success: true, data: rows });
  } catch (error) {
    console.error('获取关注列表错误:', error);
    res.status(500).json({ success: false, message: '服务器错误' });
  }
});

// 获取粉丝列表
app.get('/api/followers/:userId', async (req, res) => {
  try {
    const { userId } = req.params;
    const [rows] = await pool.execute(`
      SELECT f.user_id, u.name, u.avatar, u.signature
      FROM follows f
      LEFT JOIN users u ON f.user_id = u.id
      WHERE f.follow_id = ?
    `, [userId]);
    res.json({ success: true, data: rows });
  } catch (error) {
    console.error('获取粉丝列表错误:', error);
    res.status(500).json({ success: false, message: '服务器错误' });
  }
});

// 启动服务器
const HOST = '0.0.0.0'; // 监听所有网络接口
const ACTUAL_IP = '10.133.25.98'; // 您的实际WLAN IP地址

app.listen(PORT, HOST, () => {
  console.log(`🚀 API服务器运行在 http://localhost:${PORT}`);
  console.log(`📱 您的HarmonyOS应用可以连接到: http://localhost:${PORT}/api`);
  console.log(`🌐 或者使用实际IP地址: http://${ACTUAL_IP}:${PORT}/api`);
  console.log(`🔧 服务器监听地址: ${HOST}:${PORT}`);
});

module.exports = app; 